package controller

import (
	"github.com/duke-git/lancet/v2/convertor"
	"github.com/gin-gonic/gin"
	"kf/common"
	"kf/models/dao"
	"kf/models/entity"
	"kf/utils/R"
	"net/http"
	"strconv"
)

// 黑名单
type IpController struct {
	IpBlackDao *dao.IpBlackDao
}
type Ip struct {
	Ip string `json:"ip"`
}

// 添加黑名单PostFormMap
func (ipController *IpController) PostIpBlack(c *gin.Context) {
	var ip Ip
	err := c.ShouldBindJSON(&ip)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg("加入黑名单失败"))
		return
	}
	if ip.Ip == "" {
		c.JSON(http.StatusOK, R.ReturnFailMsg("请输入IP!"))
		return
	}
	kefuId, _ := c.Get("kefu_name")
	ipController.IpBlackDao.CreateIpblack(ip.Ip, kefuId.(string))
	c.JSON(http.StatusOK, R.ReturnSuccess("添加黑名单成功"))
}

// 删除黑名单
func (ipController *IpController) DelIpBlack(c *gin.Context) {
	ip := c.Query("ip")
	if ip == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "请输入IP!",
		})
		return
	}
	ipController.IpBlackDao.DeleteIpBlackByIp(ip)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除黑名单成功!",
	})
}
func (ipController *IpController) GetIpBlacks(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	if page == 0 {
		page = 1
	}
	count := ipController.IpBlackDao.CountIps(nil, nil)
	list := ipController.IpBlackDao.PageIps(nil, nil, uint(page), common.VisitorPageSize)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"result": gin.H{
			"list":     list,
			"count":    count,
			"pagesize": common.PageSize,
		},
	})
}
func (ipController *IpController) GetIpblacksByKefuId(c *gin.Context) {
	kefuId, _ := c.Get("kefu_id")
	toInt := convertor.ToString(kefuId)
	list := ipController.IpBlackDao.FindIpsByKefuId(toInt)
	c.JSON(http.StatusOK, R.ReturnSuccess(list))
}

// 分页获取黑名单
func (ipController *IpController) Page(context *gin.Context) {
	var pageQuery entity.IpBlackPageQuery
	err := context.ShouldBindQuery(&pageQuery)
	if err != nil {
		context.JSON(http.StatusInternalServerError, R.ReturnFailMsg(err.Error()))
		return
	}
	page := pageQuery.PageQuery.PageNum
	pageSize := pageQuery.PageQuery.PageSize
	ip := pageQuery.IP
	var query any
	var arg []any
	if ip == nil || *ip == "" {
		query = nil
		arg = nil
	} else {
		query = "ip = ?"
		arg = append(arg, ip)
	}
	count := ipController.IpBlackDao.CountIps(query, arg)
	list := ipController.IpBlackDao.PageKeFuIps(query, arg, uint(*page), uint(*pageSize))
	var listVo []entity.IpBlackPageVo
	for _, blackPage := range list {
		vo := entity.IpBlackPageVo{
			ID:       blackPage.ID,
			IP:       blackPage.IP,
			KefuId:   blackPage.KefuId,
			KefuName: blackPage.KefuName,
			CreateAt: blackPage.CreateAt.Format("2006-01-02 15:04:05"),
		}
		listVo = append(listVo, vo)
	}
	if err != nil {
		context.JSON(http.StatusInternalServerError, R.ReturnFailMsg(err.Error()))
		return
	}
	context.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "ok",
		"data": gin.H{
			"list":  listVo,
			"count": count,
		},
	})
}
